"use client"

import { Button, ButtonGroup } from "@nextui-org/button";
import { Card, CardBody, CardHeader } from "@nextui-org/card";
import { Avatar, Badge, Popover, PopoverContent, PopoverTrigger, Progress, useDisclosure } from "@nextui-org/react";
import Personal from "./components/Personal";
import { useEffect, useRef, useState } from "react";
import { selectUserDetail } from "@/lib/features/login/loginSlice";
import { useAppDispatch, useAppSelector } from "@/lib/hooks";
import AddFlag from "./components/AddFlag";
import { getFlags } from "@/api/flag/get";
import { selectFlagDetail, setFlagData } from "@/lib/features/flag/flagSlice";
import CompleteFlag from "./components/CompleteFlag";
import { redirect, RedirectType } from "next/navigation";
import computedDayCount from "@/utils/date";
import { unicodeToEmoji } from "@/utils/randomemoji";
import { AddFlagParams } from "@/type/flag";
import { isCodeMessage } from "@/api/config";
import AddTeam from "./components/AddTeam";
import { getLeaveTeam, getTeam } from "@/api/team/get";
import { selectTeamLeaveDetail, setLeaveTeamData, setTeamData } from "@/lib/features/team/teamSlice";
import { selectTeamDetail } from "@/lib/features/team/teamSlice";
import LeaveTeam from "./components/LeaveTeam";
import JoinTeam from "./components/JoinTeam";
import { getJoinTeam } from "@/api/team/tember/join";
import { selectjoinTeamDetail, setjoinTeamData } from "@/lib/features/join/joinSlice";

// 创建个人图标
const CreatedIcon = ({ size, ...props }: { size: number }) => {
    return (
        <>
            <svg className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
                {...props}
                p-id="7580" height={size || 24} width={size || 24}>
                <path d="M588.8 435.2h358.4a76.8 76.8 0 1 1 0 153.6h-358.4v358.4a76.8 76.8 0 1 1-153.6 0v-358.4h-358.4a76.8 76.8 0 1 1 0-153.6h358.4v-358.4a76.8 76.8 0 1 1 153.6 0v358.4z" fill="#cdcdcd" p-id="7581"></path>
            </svg>
        </>

    );
};

// 加入团队图标
const JoinIcon = ({ size, ...props }: { size: number }) => {
    return (
        <svg className="icon"
            {...props}
            viewBox="0 0 1024 1024"
            version="1.1" xmlns="http://www.w3.org/2000/svg"
            p-id="14907" height={size || 24} width={size || 24}>
            <path d="M901.162667 165.504A128 128 0 0 0 810.666667 128h-298.666667a128 128 0 0 0-128 128v85.333333a42.666667 42.666667 0 1 0 85.333333 0V256a42.666667 42.666667 0 0 1 42.666667-42.666667h298.666667a42.666667 42.666667 0 0 1 42.666666 42.666667v512a42.666667 42.666667 0 0 1-42.666666 42.666667h-298.666667a42.666667 42.666667 0 0 1-42.666667-42.666667v-85.333333a42.666667 42.666667 0 1 0-85.333333 0v85.333333a128 128 0 0 0 128 128h298.666667a128 128 0 0 0 128-128V256a128 128 0 0 0-37.504-90.496z" p-id="14908" fill="#cdcdcd"></path><path d="M567.168 353.834667a42.666667 42.666667 0 0 0 0 60.330666L622.336 469.333333H170.666667a42.666667 42.666667 0 1 0 0 85.333334h451.669333l-55.168 55.168a42.666667 42.666667 0 0 0 60.330667 60.330666l127.872-127.872a49.834667 49.834667 0 0 0 1.706666-1.792 42.666667 42.666667 0 0 0-1.578666-58.666666l-0.213334-0.213334-127.786666-127.786666a42.666667 42.666667 0 0 0-60.330667 0z" p-id="14909" fill="#cdcdcd"></path>
        </svg>
    )
}

// 创建团队
const CreateTeam = ({ size, ...props }: { size: number }) => {
    return (
        <svg className="icon"
            {...props}
            viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
            p-id="15956" height={size || 24} width={size || 24}>
            <path d="M133.305587 66.042135c-2.685155 0-5.370311 0.382717-8.055466 0.574075l0 890.320395 110.098537 0c0.138146-2.026146 0.357134-4.054339 0.357134-6.080485L235.705791 73.519434c0-2.38328-0.218988-4.765537-0.329505-7.504928C200.803887 66.013483 167.053202 65.986877 133.305587 66.042135zM899.281999 79.793324l0-8.055466c-2.329045 1.151219-3.508917 1.698688-4.629437 2.330068-48.654117 27.036773-100.319823 45.884027-155.054425 55.855122-59.499116 10.849092-118.343315 9.04091-176.445618-9.533121C491.925291 97.655134 419.576519 79.548754 344.816838 72.834842c-17.503653-1.588171-35.119869-1.7519-53.254901-2.629897l0 558.736441c2.301416-1.475608 3.971451-2.490727 5.615904-3.615341 39.969317-26.709315 82.787518-47.444569 129.054261-60.650335 69.828368-19.887956 138.316206-19.340487 205.075679 12.983709 26.983561 13.041014 55.638181 21.559015 85.554538 25.229614 35.775808 4.411473 70.101591 0.055259 101.467973-18.902512 34.626635-20.900006 56.541761-52.29504 70.729901-89.333608 4.714372-12.325723 9.699919-25.584702 9.783831-38.45994C899.583874 330.726423 899.281999 205.25885 899.281999 79.793324z" fill="#cdcdcd" p-id="15957"></path></svg>
    )
}

// flag 结案
const FlagEnd = ({ size, ...props }: { size: number }) => {
    return (
        <svg className="icon" {...props} viewBox="0 0 1401 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="21844"
            height={size || 24} width={size || 24}>
            <path d="M1309.423 66.312c-20.813-21.184-49.766-34.312-81.786-34.312s-60.971 13.128-81.769 34.295l-643.994 643.995-270.471-261.455c-20.91-24.288-51.695-39.573-86.048-39.573-62.596 0-113.34 50.744-113.34 113.34 0 34.997 15.862 66.29 40.789 87.080l340.202 342.743v6.44c20.891 20.489 49.539 33.135 81.142 33.135s60.25-12.646 81.159-33.154l734.116-730.253c21.112-20.605 34.207-49.344 34.207-81.142s-13.094-60.536-34.184-81.119z" p-id="21845" fill="#cdcdcd"></path></svg>
    )
}

const TeamLeave = ({ size, ...props }: { size: number }) => {
    return (
        <svg className="icon" {...props} viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5208" height={size || 24} width={size || 24}>
            <path d="M453.176889 568.547556a250.823111 250.823111 0 0 0 179.313778-74.922667 257.536 257.536 0 0 0 0-361.813333 252.131556 252.131556 0 0 0-358.627556 0 257.536 257.536 0 0 0 0 361.813333 250.823111 250.823111 0 0 0 179.313778 74.922667z m0-432.981334c96.824889 0 175.616 79.473778 175.616 177.152 0 97.678222-78.791111 177.208889-175.616 177.208889-96.824889 0-175.616-79.530667-175.616-177.208889 0-97.678222 78.791111-177.152 175.616-177.152z m338.602667 499.427556v202.069333l77.596444-77.027555 51.996444 51.484444-166.286222 164.807111-166.286222-164.807111 51.939556-51.484444 77.596444 77.027555v-202.069333h73.386667z m-338.716445-15.36a335.644444 335.644444 0 0 0-239.957333 100.408889A342.016 342.016 0 0 0 113.777778 957.44v0.625778h77.937778v-0.568889c0.512-28.330667 5.518222-56.490667 14.961777-83.285333a261.688889 261.688889 0 0 1 97.052445-128.568889 258.958222 258.958222 0 0 1 230.456889-34.247111l0.910222 0.227555v-81.92l-0.568889-0.113778a337.692444 337.692444 0 0 0-81.464889-9.955555z" fill="#cdcdcd" p-id="5209"></path></svg>
    )
}



const Home = () => {

    const [isOpenPersonal, setIsOpenPersonal] = useState(false)

    const [isOpenFlag, setIsOpenFlag] = useState(false)
    const [isOpenTeam, setIsOpenTeam] = useState(false)
    const [isOpenLeaveTeam, setIsOpenLeaveTeam] = useState(false)
    const [isOpenTeamPopover, setIsOpenTeamPopover] = useState(false)
    const [isOpenJoinTeamPopover, setIsOpenJoinTeamPopover] = useState(false)
    const [isOpenJoinTeam, setIsOpenJoinTeam] = useState(false)

    const [isOpens, setIsOpens] = useState<boolean[]>([])

    const { username, email, user_id } = useAppSelector(selectUserDetail)

    const dispatch = useAppDispatch()

    const lastTap = useRef(0); // 记录上一次触摸的时间
    const timeoutRef = useRef<ReturnType<typeof setTimeout>>(null); // 用于延迟单击事件的触发

    const handleTouchEnd = (flag_id: number) => {
        if (flag_id === undefined) return
        const now = Date.now();
        const DOUBLE_PRESS_DELAY = 300; // 双击时间间隔阈值（单位：毫秒）

        if (now - lastTap.current < DOUBLE_PRESS_DELAY) {
            // 双击事件
            clearTimeout(timeoutRef.current as ReturnType<typeof setTimeout>); // 取消单击事件的触发
            lastTap.current = 0; // 重置时间
            redirect(`/flag/dashboard/${flag_id}`, RedirectType.push)
        } else {
            // 单击事件
            lastTap.current = now;
            timeoutRef.current = setTimeout(() => {
            }, DOUBLE_PRESS_DELAY);
        }
    };

    const handleTouchEndByTeam = (team_id: number) => {
        if (team_id === undefined) return
        const now = Date.now();
        const DOUBLE_PRESS_DELAY = 300; // 双击时间间隔阈值（单位：毫秒）

        if (now - lastTap.current < DOUBLE_PRESS_DELAY) {
            // 双击事件
            clearTimeout(timeoutRef.current as ReturnType<typeof setTimeout>); // 取消单击事件的触发
            lastTap.current = 0; // 重置时间
            redirect(`/team/dashboard/${team_id}`, RedirectType.push)
        } else {
            // 单击事件
            lastTap.current = now;
            timeoutRef.current = setTimeout(() => {
            }, DOUBLE_PRESS_DELAY);
        }
    };

    const { flags } = useAppSelector(selectFlagDetail) ?? {}
    const { team_name, team_id, emoji } = useAppSelector(selectTeamDetail) ?? {}
    const joinData = useAppSelector(selectjoinTeamDetail) ?? {}
    const { leaveTeam } = useAppSelector(selectTeamLeaveDetail) ?? {}

    const hasOver = (): boolean => {
        return flags.filter(v => v.over).length > 0
    }

    const { isOpen, onOpen, onOpenChange } = useDisclosure();

    useEffect(() => {
        let ignore = false
        async function getFlagData() {
            if (email != null && email != "") {
                const { data } = await getFlags(email)
                const { data: { team } } = await getTeam(email)
                const result = await getJoinTeam(user_id as number)
                const { data: { teams } } = await getLeaveTeam(email)
                if (email === data.email) {
                    if (!ignore) {
                        dispatch(setFlagData(data))
                        dispatch(setTeamData(team))
                        dispatch(setLeaveTeamData(teams))
                        if (result.code == 200) {
                            dispatch(setjoinTeamData(result.data[0]))
                        }
                    }
                }
            } else {
                // 未授权响应
                if (!ignore) {
                    await isCodeMessage(
                        new Response("Unauthorized: Access denied", {
                            status: 401, // 设置状态码为 401 Bad Request
                            statusText: 'Unauthorized: Access denied', // 可选：设置状态文本
                        })
                    )
                }

            }
        }
        timeoutRef.current = setTimeout(() => {
        }, 20);
        getFlagData()
        return () => {
            ignore = true
            clearTimeout(timeoutRef.current as ReturnType<typeof setTimeout>);
        }
    }, [dispatch, email, isOpenTeam])

    const openCurrentPopover = (i: number) => {
        isOpens[i] = true
        setIsOpens([...isOpens])
    }

    const closeCurrentPopover = (i: number) => {
        isOpens[i] = false
        setIsOpens([...isOpens])
    }


    return (
        <>
            <div>
                <div className="flex justify-center items-center mb-4">
                    <div>
                        <Button onPress={() => setIsOpenPersonal(true)} isIconOnly size="lg" color="danger" variant="faded">
                            <Avatar radius="md" color="warning" />
                        </Button>
                    </div>
                </div>
                <div className={`"flex justify-around flex-row`}>
                    <Card
                        isBlurred
                        className={"bg-background/60 border-none p-2 rounded-lg dark:bg-default-100/50 w-[300px] m-4"}
                        shadow="md"
                    >
                        <CardHeader>
                            <h1>Craete your flag</h1>
                        </CardHeader>
                        <CardBody className="scrollbar-hide flex flex-row">
                            {
                                flags.filter(v => !v.over)?.map((flag: AddFlagParams, i) => {
                                    // console.log("emoji: "+unicodeToEmoji(flag.emoji as number));

                                    return (
                                        <Popover className="max-h-max" isOpen={isOpens[i]} key={i + 'p'} placement="top">
                                            <PopoverTrigger>
                                                <Button
                                                    onTouchEnd={() => handleTouchEnd(flag.flag_id as number)}
                                                    onDoubleClick={() => redirect(`/flag/dashboard/${flag.flag_id}`, RedirectType.push)} onMouseLeave={() => closeCurrentPopover(i)} onMouseEnter={() => openCurrentPopover(i)} key={i + 'b'} className="mx-[3px] flex items-center justify-center" isIconOnly size="lg" color="success" variant="solid">
                                                    <Avatar key={i + 'a'} icon={<span className="text-3xl">{unicodeToEmoji(flag.emoji as number)}</span>} radius="md" color="success" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="text-white">
                                                <div className="px-1 py-2">
                                                    <Avatar icon={<span className="text-3xl">{unicodeToEmoji(flag.emoji as number)}</span>} radius="md" color="success" />

                                                    <div className="text-small font-bold">Plan description</div>
                                                    <div className="text-tiny text-slate-300">{flag.description}</div>
                                                    <div className="text-small font-bold">Clocking time</div>
                                                    <div className="text-tiny text-slate-300">{flag.checktime ?? 'Anytime'}</div>
                                                    <div className="text-small font-bold">Start Date</div>
                                                    <div className="text-tiny text-slate-300">{flag.start}</div>
                                                    <div className="text-small font-bold">End Date</div>
                                                    <div className="text-tiny text-slate-300">{flag.period}</div>
                                                    <div className="text-small font-bold">Schedule</div>
                                                    <div className="text-tiny text-slate-300">
                                                        <Progress aria-label="Loading..." label={'Planned days：' + computedDayCount(flag.start, flag.period) + ' | Completed days：'} showValueLabel={true} maxValue={100} color="secondary" value={(computedDayCount(new Date().toLocaleString(), flag.period) * computedDayCount(flag.start, flag.period)) / 100} />
                                                    </div>
                                                </div>
                                            </PopoverContent>
                                        </Popover>
                                    )
                                })
                            }
                            {
                                hasOver() ? (
                                    <Badge color="danger" placement="bottom-right" size="sm" content={flags.filter(v => v.over).length}>
                                        <ButtonGroup className="mx-[3px]">

                                            <Button onPress={() => setIsOpenFlag(true)} isIconOnly size="lg" color="success" variant="ghost">
                                                <CreatedIcon size={32} />
                                            </Button>

                                            {
                                                flags.filter(v => v.over).length > 0 &&
                                                <Button onPress={() => onOpen()} isIconOnly size="lg" color="success" variant="ghost">
                                                    <FlagEnd size={32} />
                                                </Button>
                                            }

                                        </ButtonGroup>
                                    </Badge>
                                ) : (
                                    <Button onPress={() => setIsOpenFlag(true)} isIconOnly size="lg" color="success" variant="ghost">
                                        <CreatedIcon size={32} />
                                    </Button>
                                )
                            }


                        </CardBody>
                    </Card>
                    <Card
                        isBlurred
                        className={"bg-background/60 border-none p-2 rounded-lg dark:bg-default-100/50 w-[300px] m-4"}
                        shadow="md"
                    >
                        <CardHeader>
                            <h1>Craete your team</h1>
                        </CardHeader>
                        <CardBody className="scrollbar-hide flex flex-row">
                            {
                                team_id != null && team_name != "" ?
                                    (<>
                                        <Popover isOpen={isOpenTeamPopover} className="max-h-max" placement="top">
                                            <PopoverTrigger>
                                                <Button
                                                    onMouseLeave={() => setIsOpenTeamPopover(false)} onMouseEnter={() => setIsOpenTeamPopover(true)}
                                                    onTouchEnd={() => handleTouchEndByTeam(team_id)}
                                                    onDoubleClick={() => redirect(`/team/dashboard/${team_id}`, RedirectType.push)}
                                                    className="mx-[3px] flex items-center justify-center" isIconOnly size="lg" color="warning" variant="ghost">
                                                    <Avatar icon={<span className="text-3xl">{unicodeToEmoji(emoji ?? 0x1F680)}</span>} radius="md" color="warning" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="text-white">
                                                <div className="px-1 py-2">
                                                    <Avatar icon={<span className="text-xl">{unicodeToEmoji(emoji ?? 0x1F680)}</span>} size="sm" radius="md" color="warning" />
                                                    <div className="text-small font-bold">
                                                        Team ID
                                                        <div className="text-tiny text-slate-300">{team_id}</div>
                                                        Team Name
                                                        <div className="text-tiny text-slate-300">{team_name}</div>
                                                    </div>
                                                </div>
                                            </PopoverContent>
                                        </Popover>
                                        {
                                            leaveTeam.length > 0 &&
                                            (<>
                                                <Badge color="danger" placement="bottom-right" size="sm" content={leaveTeam.length}>
                                                    <Button onPress={() => setIsOpenLeaveTeam(true)} isIconOnly size="lg" color="warning" variant="ghost">
                                                        <TeamLeave size={32} />
                                                    </Button>
                                                </Badge>
                                            </>)
                                        }
                                    </>)
                                    : (<>
                                        <Button isIconOnly size="lg" variant="ghost" color="warning" onPressEnd={() => setIsOpenTeam(true)}>
                                            <CreateTeam size={32} />
                                        </Button>
                                    </>)
                            }
                        </CardBody>
                    </Card>
                    <Card
                        isBlurred
                        className={"bg-background/60 border-none p-2 rounded-lg dark:bg-default-100/50 w-[300px] m-4"}
                        shadow="md"
                    >
                        <CardHeader>
                            <h1>Join your team</h1>
                        </CardHeader>
                        <CardBody className="scrollbar-hide flex ">
                            {
                                joinData.team_id != null && joinData.team_name != "" && joinData.user_id != user_id ? (
                                    <>
                                        <Popover isOpen={isOpenJoinTeamPopover} className="max-h-max" placement="top">
                                            <PopoverTrigger>
                                                <Button
                                                    onMouseLeave={() => setIsOpenJoinTeamPopover(false)} onMouseEnter={() => setIsOpenJoinTeamPopover(true)}
                                                    onTouchEnd={() => handleTouchEndByTeam(joinData.team_id as number)}
                                                    onDoubleClick={() => redirect(`/team/dashboard/${team_id}`, RedirectType.push)}
                                                    className="mx-[3px] flex items-center justify-center" isIconOnly size="lg" color="warning" variant="ghost">
                                                    <Avatar icon={<span className="text-3xl">{unicodeToEmoji(joinData.emoji ?? 0x1F680)}</span>} radius="md" color="warning" />
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent className="text-white">
                                                <div className="px-1 py-2">
                                                    <Avatar icon={<span className="text-xl">{unicodeToEmoji(joinData.emoji ?? 0x1F680)}</span>} size="sm" radius="md" color="warning" />
                                                    <div className="text-small font-bold">
                                                        Team ID
                                                        <div className="text-tiny text-slate-300">{joinData.team_id}</div>
                                                        Team Name
                                                        <div className="text-tiny text-slate-300">{joinData.team_name}</div>
                                                    </div>
                                                </div>
                                            </PopoverContent>
                                        </Popover>
                                    </>
                                ) : (
                                    <>
                                        <Button onPress={() => setIsOpenJoinTeam(true)} isIconOnly size="lg" variant="ghost" color="danger">
                                            <JoinIcon size={32} />
                                        </Button>
                                    </>
                                )
                            }
                        </CardBody>
                    </Card>
                </div>
            </div >
            <AddFlag isOpen={isOpenFlag} onClose={() => setIsOpenFlag(false)} />
            <JoinTeam onOpenChange={() => setIsOpenJoinTeam(!isOpenJoinTeam)} isOpen={isOpenJoinTeam} onCloseCurrent={() => setIsOpenJoinTeam(false)} />
            <AddTeam isOpen={isOpenTeam} onClose={() => setIsOpenTeam(false)} />
            <Personal username={username} email={email} isOpen={isOpenPersonal} onClose={() => setIsOpenPersonal(false)} />
            <CompleteFlag {...{ isOpen, onOpen, onOpenChange }} />
            <LeaveTeam isOpen={isOpenLeaveTeam} onClose={() => setIsOpenLeaveTeam(false)} />
        </>
    )
}
export default Home;